﻿$().ready(function () {
    $("#optItem").attr("class", "HoverOnList");
    $("#breadcrumb").append('<li><a href="' + $("#urlProduct").val() + '" title="Productos">Productos</a></li>');

    ///Toolbar
    $('#btnClear').live('click', function () {
        ClearForm();
    });

    $('#btnNew').live('click', function () {
        if (confirm('¿Desea abandonar la edición y crear un registro nuevo?')) {
            window.location = $('#urlCreate').val();
        }
    });

    ///Menu
    $('#menuClear').live('click', function () {
        ClearForm();
    });

    $('#menuNew').live('click', function () {
        if (confirm('¿Desea abandonar la edición y crear un registro nuevo?')) {
            window.location = $('#urlCreate').val();
        }
    });

    $('#btnSearch').click(function () {
        Search();
    });

    $('#btnSave').click(function () {
        //Upload();

        if ($("#frmProduct").valid()) {
            var list = new Array();
            $('#lstIdentificationsList li').each(function () {
                    var current = $(this); 
                    var item = current.attr("identificationTypeID") + ";" + current.attr("identificationValue");
                    list.push(item);
            });

            var componentlist = new Array();
            $('#lstProductList li').each(function () {
                var currentCom = $(this);
                var itemCom = currentCom.attr("productID") + ";" + currentCom.attr("productComponentTypeID") + ";" + currentCom.attr("quantity") + ";" + currentCom.attr("comments");
                componentlist.push(itemCom);
            });

            if (list.length > 0 && componentlist.length > 0) {
                    Add();
                }
                else {
                    alert('Debe ingresar al menos una identifcacion al listado');
                }
            }
    });

    $('#menuSave').click(function () {
        Upload();
    });

    $('.item-del').live('click', function () {
        if (confirm('¿Esta seguro que desea eliminar el registro?')) {
            $(this).closest('li').remove();
        }
    });

    //Lists
    $('#btnAddIdentification').click(function () {
        AddRecord();
    });

    $('#btnAddComponent').click(function () {
        AddComponentRecord();
    });

    $('#btnAddCost').click(function () {
        AddCostRecord();
    });

    ///Forms
    if (!(typeof $('#txtProductFilter')[0] === "undefined")) {
        InitAutocomplete();
    }

    $("#txtStartDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtEndDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtExpirationDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtProductCostStartDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtProductCostEndDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtQuantity").spinner({
        min: 0,
        step: 1,
        start: 0,
        numberFormat: "n"
    });

    $("#txtFeatureCost").spinner({
        min: 0,
        step: 1,
        start: 0,
        numberFormat: "C"
    });

    $("#txtCost").spinner({
        min: 0,
        step: 1,
        start: 0,
        numberFormat: "C"
    });

    $("#txtFeaturePrice").spinner({
        min: 0,
        step: 1,
        start: 0,
        numberFormat: "C"
    });

    $("#txtProductPrice").spinner({
        min: 0,
        step: 1,
        start: 0,
        numberFormat: "C"
    });

    $("#uploader").pluploadQueue({
        // General settings
        runtimes: 'gears,flash,silverlight,browserplus,html5',
        url: $("#urlUpload").val(),
        max_file_size: '10mb',
        chunk_size: '1mb',
        unique_names: true,
        // Resize images on clientside if we can
        resize: { width: 320, height: 240, quality: 90 },
        // Specify what files to browse for
        filters: [
            { title: "Image files", extensions: "jpg,gif,png" }
        ],
        // Flash settings
        flash_swf_url: $("#urlUploadFlash").val(),
        // Silverlight settings
        silverlight_xap_url: $("#urlUploadSilverlight").val()
    });

    LoadGallerySetting();
});

function LoadGallerySetting() {
    // We only want these styles applied when javascript is enabled
    $('div.content').css('display', 'block');

    // Initially set opacity on thumbs and add
    // additional styling for hover effect on thumbs
    var onMouseOutOpacity = 0.67;
    $('#thumbs ul.thumbs li, div.navigation a.pageLink').opacityrollover({
        mouseOutOpacity: onMouseOutOpacity,
        mouseOverOpacity: 1.0,
        fadeSpeed: 'fast',
        exemptionSelector: '.selected'
    });

    // Initialize Advanced Galleriffic Gallery
    var gallery = $('#thumbs').galleriffic({
        delay: 2500,
        numThumbs: 10,
        preloadAhead: 10,
        enableTopPager: false,
        enableBottomPager: false,
        imageContainerSel: '#slideshow',
        controlsContainerSel: '#controls',
        captionContainerSel: '#caption',
        loadingContainerSel: '#loading',
        renderSSControls: true,
        renderNavControls: true,
        playLinkText: 'Play Slideshow',
        pauseLinkText: 'Pause Slideshow',
        prevLinkText: '&lsaquo; Previous Photo',
        nextLinkText: 'Next Photo &rsaquo;',
        nextPageLinkText: 'Next &rsaquo;',
        prevPageLinkText: '&lsaquo; Prev',
        enableHistory: true,
        autoStart: false,
        syncTransitions: true,
        defaultTransitionDuration: 900,
        onSlideChange: function (prevIndex, nextIndex) {
            // 'this' refers to the gallery, which is an extension of $('#thumbs')
            this.find('ul.thumbs').children()
                .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
                .eq(nextIndex).fadeTo('fast', 1.0);

            // Update the photo index display
            this.$captionContainer.find('div.photo-index')
                .html('Photo ' + (nextIndex + 1) + ' of ' + this.data.length);
        },
        onPageTransitionOut: function (callback) {
            this.fadeTo('fast', 0.0, callback);
        },
        onPageTransitionIn: function () {
            var prevPageLink = this.find('a.prev').css('visibility', 'hidden');
            var nextPageLink = this.find('a.next').css('visibility', 'hidden');

            // Show appropriate next / prev page links
            if (this.displayedPage > 0)
                prevPageLink.css('visibility', 'visible');

            var lastPage = this.getNumPages() - 1;
            if (this.displayedPage < lastPage)
                nextPageLink.css('visibility', 'visible');

            this.fadeTo('fast', 1.0);
        }
    });

    /**************** Event handlers for custom next / prev page links **********************/

    gallery.find('a.prev').click(function (e) {
        gallery.previousPage();
        e.preventDefault();
    });

    gallery.find('a.next').click(function (e) {
        gallery.nextPage();
        e.preventDefault();
    });

    /****************************************************************************************/

    /**** Functions to support integration of galleriffic with the jquery.history plugin ****/

    // PageLoad function
    // This function is called when:
    // 1. after calling $.historyInit();
    // 2. after calling $.historyLoad();
    // 3. after pushing "Go Back" button of a browser
    function pageload(hash) {
        // alert("pageload: " + hash);
        // hash doesn't contain the first # character.
        if (hash) {
            $.galleriffic.gotoImage(hash);
        } else {
            gallery.gotoIndex(0);
        }
    }

    // Initialize history plugin.
    // The callback is called at once by present location.hash. 
    $.historyInit(pageload, "advanced.html");

    // set onlick event for buttons using the jQuery 1.3 live method
    $("a[rel='history']").live('click', function (e) {
        if (e.button != 0) return true;

        var hash = this.href;
        hash = hash.replace(/^.*#/, '');

        // moves to a new page. 
        // pageload is called at once. 
        // hash don't contain "#", "?"
        $.historyLoad(hash);

        return false;
    });

    /****************************************************************************************/
}

function ConfirmDelete(id) {
    if (confirm('¿Esta seguro que desea eliminar el registro?')) {
        DeleteProduct(id);
    }
}

function DeleteProduct(objectId) {
    $.ajax(
    {
        type: "POST",
        url: $('#urlDelete').val(),
        data:
            JSON.stringify({
                id: objectId
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = "/ODSYSUI/Product/SetMessage?id=1";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = "/ODSYSUI/Product/SetMessage?id=2";
        }
    });
}

function ClearForm() {

    var cmbProductType = $('#cmbProductType');
    if (cmbProductType.length > 0) {
        cmbProductType[0].selectedIndex = 0;
    }

    $('#txtName').val('');
    $('#txtDose').val('');
    $('#txtPrecaution').val('');
    $('#txtPotency').val('');
    $('#txtObservations').val('');

    $('.field-validation-error').remove();
    $(":input").removeClass("input-validation-error");
}

function Search() {
    var startDate = $('#txtStartDate').val();
    var endDate = $('#txtEndDate').val();
    var date1 = null;
    var date2 = null;

    if (startDate != "") {
        var d1 = parseInt(startDate.substring(0, 2));
        var m1 = parseInt(startDate.substring(3, 5)) - 1;
        var y1 = parseInt(startDate.substring(6, 10));
        date1 = new Date(y1, m1, d1);
    }

    if (endDate != "") {
        var d1 = parseInt(endDate.substring(0, 2));
        var m1 = parseInt(endDate.substring(3, 5)) - 1;
        var y1 = parseInt(endDate.substring(6, 10));
        date2 = new Date(y1, m1, d1);
    }

    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlSearch").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                productCategoryID: $('#cmbProductCategory').val(),
                ProductTypeID: $('#cmbProductType').val(),
                name: $('#txtName').val(),
                startDate: date1,
                endDate: date2,
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = $("#urlSearch").val();
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            debugger;
            //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}

function Upload() {
    var uploader = $('#uploader').pluploadQueue();
    // Files in queue upload them first

    if (uploader.files.length > 0) {
        // When all files are uploaded submit form
        uploader.bind('StateChanged', function () {
            if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
                //$('form')[0].submit();
            }
        });

        uploader.start();
    } else {
        alert('You must queue at least one file.');
    }

    return false;
}

function AddRecord() {
    var identificationTypeID = $('#cmbIdentificationType').val();
    if (identificationTypeID != '') {
        if ($("#frmProduct").valid()) {

            var item = "<li identificationTypeID='" + $('#cmbIdentificationType').val() + "' identificationValue='" + $('#txtIdentificationValue').val() + "'>" +
                            "<table style='width: 100%;'>" +
                                "<tr>" +
                                    "<td style='width: 14%; text-align: left;'>" + $('#cmbIdentificationType>option:selected').text() + "</td>" +
                                    "<td style='width: 58%; text-align: left;'>" + $('#txtIdentificationValue').val() + "</td>" +
                                "</tr>" +
                             "</table>" +
                             "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
                        "</li>";

            $("#identificationList ul").append(item);
         //   Clear();
        }
    }
    else {
        alert('Debe seleccionar una identificacion.');
    }
}

function AddComponentRecord() {
    var productID = $('#productID').val();
    if (productID != '' && $('#txtQuantity').val() > 0) {
        if ($("#frmProduct").valid()) {

            var item = "<li productID='" + $('#productID').val() + "' productComponentTypeID='" + $('#cmbProductType').val() + "' quantity='" + $('#txtQuantity').val() + "' comments='" + $('#txtComments').val() + "'>" +
                            "<table style='width: 100%;'>" +
                                "<tr>" +
                                    "<td style='width: 20%; text-align: left;'>" + $('#txtProductFilter').val() + "</td>" +
                                    "<td style='width: 60%; text-align: left;'>" + $('#txtQuantity').val() + "</td>" +
                                "</tr>" +
                             "</table>" +
                             "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
                        "</li>";

            $("#ProductList ul").append(item);
          //  Clear();
        }
    }
    else {
        alert('Debe seleccionar un componente y la cantidad debe ser mayor a 0.');
    }
}

function AddCostRecord() {
    if ( $('#txtCost').val() > 0) {
        if ($("#frmProduct").valid()) {

            var item = "<li geographicBoundaryID='" + $('#geographicBoundaryID').val() + "' productCostTypeID='" + $('#cmbProductCostType').val() + "' productCostCurrencyID='" + $('#cmbProductCostCurrency').val() + "'>" +
                            "<table style='width: 100%;'>" + 
                                "<tr>" +
                                    "<td style='width: 33%; text-align: left;'>" + $('#cmbGeographicBoundary>option:selected').text() + "</td>" +
                                    "<td style='width: 35%; text-align: left;'>" + $('#cmbProductCostType>option:selected').text() + "</td>" +
                                    "<td style='width: 45%; text-align: left;'>" + $('#cmbProductCostCurrency>option:selected').text() + "</td>" +
                                    "<td style='width: 60%; text-align: left;'>" + $('#txtCost').val() + "</td>" +
                                "</tr>" +
                             "</table>" +
                             "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
                        "</li>";
            debugger;
            $("#CostList ul").append(item);
            //Clear();
        }
    }
    else {
        alert('Debe seleccionar todos los campos que lo requieren y el costo debe ser mayor a 0.');
    }
}

function InitAutocomplete() {
    $("#txtProductFilter").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: $('#urlGetProducts').val(),
                dataType: "json",
                data: {
                    searchString: request.term,
                    IsByName: $('#rdbNameFilter').is(':checked'),
                    maxRows: 12
                },
                parse: function (data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i].name, result: data[i].name };
                    }
                    return rows;
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.code + " - " + item.name,
                            ID: item.productID,
                            ProviderID: item.providerID,
                            Code: item.code,
                            Name: item.name,
                            Cost: item.cost,
                            Price: item.price,
                            TotalPrice: item.totalPrice,
                            CurrentExistence: item.currentExistence
                        }
                    }));
                },
                error: function (data, status, e) {
                    alert(e);
                }
            });
        },
        minLength: 0,
        select: function (event, ui) {
            $('#productID').val(ui.item.ID);
            $('#productName').val(ui.item.name);
        }
    });

    $("#txtItemFilter").keyup(function () {
        if (!this.value) {
            $('#productID').val();
        }
    });
}

function Add() {
    var list = new Array();
    $('#lstIdentificationsList li').each(function () {
        var current = $(this);
        var item = current.attr("identificationTypeID") + ";" + current.attr("identificationValue");
        list.push(item);
    });

    var componentlist = new Array();
    $('#lstProductList li').each(function () {
        var currentCom = $(this);
        var itemCom = currentCom.attr("productID") + ";" + currentCom.attr("productComponentTypeID") + ";" + currentCom.attr("quantity") + ";" + currentCom.attr("comments");
        componentlist.push(itemCom);
    });

    debugger;
    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlCreate").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                items: list,
                Components: componentlist,
                providerID: $("#cmbProvider").val(),
                productClassificationID: $("#cmbProductClassification").val(),
                measureUnitID: $("#cmbMeasureUnit").val(),
                productCategoryID: $("#cmbProductCategory").val(),
                productTypeID: $("#CmbProductType").val(),
                expirationDate: $("#txtExpirationDate").val(),
                name: $("#txtName").val(),
                description: $("#txtDescription").val(),
                code: $("#txtCode").val(),
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                // window.location = $("#urlPrint").val();
                window.location = "/ODSYSUI/Product/SetMessage?id=3";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = "/ODSYSUI/Product/SetMessage?id=4";
        }
    });
}